package org.csu.mybigpro.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@Service
public class WebSearchService {

    @Value("${google.customsearch.api.key}")
    private String apiKey;

    @Value("${google.customsearch.cx}")
    private String searchEngineId;

    @Autowired
    private RestTemplate restTemplate; // 注入共享的、带代理的RestTemplate

    /**
     * 调用Google Custom Search API进行网络搜索
     * @param query 搜索关键词
     * @return 搜索结果的JSON字符串
     * @throws Exception API调用失败时抛出异常
     */
    public String searchWeb(String query) throws Exception {
        String encodedQuery = URLEncoder.encode(query, StandardCharsets.UTF_8);
        String url = String.format(
                "https://www.googleapis.com/customsearch/v1?key=%s&cx=%s&q=%s",
                apiKey, searchEngineId, encodedQuery
        );
        // 现在这里的restTemplate实例已经是带代理的了
        return restTemplate.getForObject(url, String.class);
    }
}